package com.example.lab.mapper;

import com.example.lab.entity.Permissions;
import com.example.lab.entity.Role;
import com.example.lab.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.lab.entity.UserRoles;
import org.apache.ibatis.annotations.*;

import java.security.Permission;
import java.util.List;

/**
 * <p>
 * 用户基础信息表 Mapper 接口
 * </p>
 *
 * @author 布莱恩
 * @since 2025-06-15
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    @Select("SELECT r.* FROM role r " +
            "JOIN user_roles ur ON r.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId}")
    @Results({
            @Result(property = "roleId", column = "role_id"),
            @Result(property = "roleName", column = "role_name"),
            @Result(property = "roleCode", column = "role_code"),
            @Result(property = "permissions", column = "role_id",
                    javaType = List.class,
                    many = @Many(select = "com.example.lab.mapper.PermissionsMapper.findByRoleId"))
    })
    List<Role> findRolesByUserId(Integer userId);

    @Select("SELECT * FROM user WHERE username = #{username}")
    User selectByUsername(String username);

    @Select("SELECT r.* FROM role r " +
            "JOIN user_roles ur ON r.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId}")
    List<Role> selectRolesByUserId(Integer userId);

    @Select("SELECT p.* FROM permissions p " +
            "JOIN role_permissions rp ON p.permission_id = rp.permission_id " +
            "JOIN user_roles ur ON rp.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId}")
    List<Permissions> selectPermissionsByUserId(Integer userId);

    @Insert("<script>" +
            "INSERT INTO user_roles (user_id, role_id) VALUES " +
            "<foreach collection='list' item='item' separator=','>" +
            "(#{item.userId}, #{item.roleId})" +
            "</foreach>" +
            "</script>")
    int batchInsertUserRoles(@Param("list") List<UserRoles> userRoles);

    @Delete("DELETE FROM user_roles WHERE user_id = #{userId}")
    int deleteUserRolesByUserId(Integer userId);

}
